package cn.signalpha.modules.social.service;

import cn.signalpha.core.tool.utils.Func;
import cn.signalpha.core.tool.utils.ObjectUtil;
import cn.signalpha.modules.social.entity.Likes;
import cn.signalpha.modules.social.mapper.LikesMapper;
import cn.signalpha.modules.social.vo.LikesVO;
import cn.signalpha.modules.social.vo.TopicVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 服务类
 *
 * @author signalpha
 */
@Service
public class LikesService extends ServiceImpl<LikesMapper, Likes> {

	/**
	 * 自定义分页
	 */
    public IPage<LikesVO> selectLikesPage(IPage<LikesVO> page, Map<String, Object> params) {
        return page.setRecords(baseMapper.selectLikesPage(page, params));
    }

	/**
	 * 自定义分页
	 */
	public IPage<TopicVO> selectLikesOnTopicPage(IPage<TopicVO> page, Map<String, Object> params) {
		return page.setRecords(baseMapper.selectLikesOnTopicPage(page, params));
	}

	/**
	 * 自定义Wrapper
	 */
	public QueryWrapper<Likes> selectLikeWrapper(Map<String, Object> params) {
		QueryWrapper<Likes> wrapper = Wrappers.query();
		wrapper.lambda().in(ObjectUtil.isNotEmpty(params.get("ids")), Likes::getId, Func.toLongList(String.valueOf(params.get("ids"))));
		wrapper.lambda().eq(ObjectUtil.isNotEmpty(params.get("userId")), Likes::getUserId, params.get("userId"));
		wrapper.lambda().eq(ObjectUtil.isNotEmpty(params.get("toUserId")), Likes::getToUserId, params.get("toUserId"));
		wrapper.lambda().eq(ObjectUtil.isNotEmpty(params.get("targetId")), Likes::getTargetId, params.get("targetId"));
		wrapper.lambda().orderByDesc(Likes::getId);
		return wrapper;
	}

	/**
	 * 数量统计
	 */
	public long countByParams(Map<String, Object> params) {
		return count(selectLikeWrapper(params));
	}

	/**
	 * 根据用户查询
	 */
	public Likes getByUserIdAndTarget(Long userId, Long targetId, Integer targetType) {
		return baseMapper.selectOne(Wrappers.<Likes>lambdaQuery().eq(Likes::getUserId, userId).eq(Likes::getTargetId, targetId).eq(Likes::getTargetType, targetType));
	}

	/**
	 * 获取点赞id
	 */
	public Long getIdByUserId(Long userId, Long targetId, Integer targetType) {
		Likes likes = getOne(Wrappers.<Likes>lambdaQuery().eq(Likes::getUserId, userId).eq(Likes::getTargetId, targetId).eq(Likes::getTargetType, targetType));
		return likes != null ? likes.getId() : 0L;
	}

}

